<template>
  <div class="app-container">
    <div class="detail-create">
      <div class="create-upload">
        <el-upload
          class="upload-demo"
          :action="importVoiceFile"
          :headers="{ token }"
          :data="{
            attraction_id
          }"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-success="handleSuccess"
          accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
        >
          <el-button plain size="mini">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 -6 24 26">
              <path
                fill="#1677ff"
                class="create-upload-svg"
                d="M11 16V7.85l-2.6 2.6L7 9l5-5l5 5l-1.4 1.45l-2.6-2.6V16zm-7 4v-5h2v3h12v-3h2v5z"
              /></svg
            ><span>Excel导入</span></el-button
          >
        </el-upload>
      </div>
    </div>

    <Table :data="list" :columns="columns" :loading="listLoading">
      <template v-slot:view_duration>
        <el-table-column label="总时长" min-width="100" prop="status" align="center">
          <template slot-scope="scope"> {{ scope.row.view_duration }}秒 </template>
        </el-table-column>
      </template>
    </Table>
  </div>
</template>

<script>
import {
  initAttractionVoice,
  updateVoiceDir,
  getUploadList,
  importVoiceFile
} from '@/api/attraction'
import { cosSign } from '@/api/common'
import { getToken } from '@/utils/auth'
export default {
  name: 'uploadList',
  components: {},
  data() {
    return {
      importVoiceFile,
      token: getToken(),
      action: '',
      attraction_id: '', //楼层uuid
      listLoading: false,
      list: [],
      columns: [
        {
          label: '编号',
          type: 'index',
          width: 60
        },
        {
          label: '景点名称',
          prop: 'view_name',
          width: 200
        },
        {
          label: '硬件ID',
          prop: 'view_id',
          width: 120
        },
        {
          label: '总时长',
          slot: 'view_duration'
        }
      ]
    }
  },
  mounted() {
    this.attraction_id = this.$route.query.id

    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getUploadList({ attraction_id: this.attraction_id }).then((res) => {
        this.list = res.data.list_data
        this.listLoading = false
      })
    },

    // 通用的上传语音包方法
    uploadVoicePackage(file, options = {}) {
      this.listLoading = true
      const formData = new FormData()
      formData.append('file', file)

      return cosSign({ scene: 'voice_init', filename: file.name }).then((response) => {
        console.log('response', response.data)
        this.action = response.data.file_url
        // 手动发起上传请求
        return fetch(response.data.presigned_url, {
          method: 'PUT',
          body: formData,
          headers: {
            token: this.token
          }
        })
          .then((res) => {
            console.log('response', res)
            this.listLoading = false

            // 根据传入的选项决定调用哪个API
            const apiParams = {
              attraction_id: this.attraction_id,
              voice_zip_file: response.data.file_url,
              ...options
            }

            const apiCall = options.dir_id
              ? updateVoiceDir(apiParams)
              : initAttractionVoice(apiParams)

            return apiCall
              .then(() => {
                this.listLoading = false
                this.$message.success('文件上传成功！')
                this.fetchData()
              })
              .catch(() => {
                this.listLoading = false
              })
          })
          .catch((err) => {
            console.log('err', err)
            this.listLoading = false
            console.error('上传失败', err)
            this.$message.error('文件上传失败！')
          })
      })
    },

    beforeUpload(file) {
      console.log('file', file)
      // 检查文件类型
      const isExcel =
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel' ||
        file.name.endsWith('.xlsx') ||
        file.name.endsWith('.xls')

      if (!isExcel) {
        this.$message.error('只能上传 Excel 文件！')
        return false
      }

      // 检查文件大小（限制为10MB）
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!')
        return false
      }

      return true // 允许上传
    },
    handleSuccess(res, file) {
      console.log('res', res)
      if (res.code === 20000) {
        this.$message.success('导入成功')
        this.fetchData()
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        })
      }
    },

    updateVoiceDir(file, dir_id) {
      // this.uploadVoicePackage(file, { dir_id })
      // 阻止 Element UI 默认上传行为
      return false
    }
  }
}
</script>

<style scoped lang="less">
.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.detail-create {
  margin-top: 10px;
  margin-bottom: 15px;
}
.input-with-select {
  width: 260px;
}
/deep/ .el-input-group__append,
.el-input-group__prepend {
  background-color: #1677ff !important;
  color: #fff !important;
  &:hover {
    background-color: #66b1ff !important;
  }
}
.detail-create {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.create-upload {
  display: flex;
  align-items: center;
  & > span {
    font-size: 12px;
    color: #666;
  }
  button {
    border-radius: 6px;
    border: 1px solid #1677ff;
    color: #1677ff;
    padding: 0 8px 5px !important;
    &:hover {
      .create-upload-svg {
        fill: #66b1ff;
      }
    }
  }
}
.edition {
  color: #666;
  font-size: 12px;
  .edition-span1 {
    margin-right: 20px;
  }
}
/deep/ .el-breadcrumb__inner.is-link {
  color: #666;
}
.dir {
  display: flex;
  align-items: center;
  cursor: pointer;
  p {
    margin-left: 5px;
  }
}
.dir-input {
  display: none;
}
</style>
